//
//  ContactViewController.m
//  UI11_Contact
//
//  Created by dllo on 15/11/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "ContactViewController.h"
#import "Student.h"
#import "AddViewController.h"
#import "ChineseToPinyin.h"

@interface ContactViewController ()<UITableViewDataSource, UITableViewDelegate, AddViewControllerDelegate>

@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) NSMutableDictionary *stuDic;
// 存排序的key
@property (nonatomic, retain) NSMutableArray *stuKeys;

@end

@implementation ContactViewController

- (void)dealloc
{
    [_tableV release];
    [_stuDic release];
    [_stuKeys release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"通讯录";
    
    [self getData];
    
    self.tableV = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(leftBarAction:)] autorelease];
    
    
  
    
}

- (void)getStuInfo:(Student *)stu
{
    NSString *key = [[ChineseToPinyin pinyinFromChiniseString:stu.name] substringToIndex:1];
    if (nil != [self.stuDic objectForKey:key]) {
        NSMutableArray *arr = [self.stuDic objectForKey:key];
        [arr addObject:stu];
    } else {
        NSMutableArray *arr = [NSMutableArray arrayWithObject:stu];
        [self.stuDic setObject:arr forKey:key];
        [self.stuKeys addObject:key];
        [self.stuKeys sortUsingSelector:@selector(compare:)];
    }
    // 别忘了刷新界面
    [self.tableV reloadData];
}

// 左键添加处理方法
- (void)leftBarAction:(UIBarButtonItem *)sender
{
//    AddViewController *addVC = [[AddViewController alloc] init];
//    [self.navigationController pushViewController:addVC animated:YES];
//    [addVC release];
    
    AddViewController *addVC = [[AddViewController alloc] init];
    addVC.delegate = self;
    UINavigationController *addNC = [[UINavigationController alloc] initWithRootViewController:addVC];
    addNC.navigationBar.translucent = NO;
    [self presentViewController:addNC animated:YES completion:^{
        
        
    }];
    
    [addVC release];
    [addNC release];
    
}

// 关联编辑键与tableView
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableV setEditing:editing animated:animated];
}

// 编写移动逻辑(限制跨区移动的情况下) - 先操作数据, 再操作UI
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSString *key = [self.stuKeys objectAtIndex:sourceIndexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    Student *stu = [[arr objectAtIndex:sourceIndexPath.row] retain];
    [arr removeObject:stu];
    
    [arr insertObject:stu atIndex:destinationIndexPath.row];
    [stu release];
    
    [self.tableV moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
 
    
}

// 限制跨区移动
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
        return sourceIndexPath;
    }
    return proposedDestinationIndexPath;
    
}



// 允许哪个cell移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 允许哪个cell编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 设置编辑类型(删除/插入/无操作)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

// 编写编辑逻辑 - 先操作数据,在操作UI - 当分区内无联系人则删除分区
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [self.stuKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [arr removeObjectAtIndex:indexPath.row];
        if (0 == arr.count) {
            [self.stuDic removeObjectForKey:key];
            [self.stuKeys removeObjectAtIndex:indexPath.section];
        
            // 删区
            [self.tableV deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
            
        } else {
            // 删行
            [self.tableV deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }

    
}

// 获取数据
- (void)getData
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HW" ofType:@"plist"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    
    self.stuDic = [NSMutableDictionary dictionary];

    
    for (NSString *key in dic) {
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSMutableDictionary *tempDic in [dic objectForKey:key]) {
            
            Student *stu = [[Student alloc] init];
            [stu setValuesForKeysWithDictionary:tempDic];
            [arr addObject:stu];
            [stu release];
        }
        [self.stuDic setObject:arr forKey:key];
    }
        // 排序
    self.stuKeys = [NSMutableArray arrayWithArray:self.stuDic.allKeys];
    [self.stuKeys sortUsingSelector:@selector(compare:)];

}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

// 设置右排索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.stuKeys;
}


// 设置每个分区的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.stuKeys objectAtIndex:section];
}

// 设置分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.stuKeys.count;
}


// 设置每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 根据排好序的数组获取key, 输出的value也是有序的
    NSString *key = [self.stuKeys objectAtIndex:section];
    return [[self.stuDic objectForKey:key] count];


}
// 创建cell(重用池), 显示每个cell上铺建的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellStr] autorelease];
    }
    
    NSString *key = [self.stuKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    Student *stu = [arr objectAtIndex:indexPath.row];
    cell.textLabel.text = stu.name;
    cell.detailTextLabel.text = stu.phone;
//    cell.imageView.image = [UIImage imageNamed:stu.image];
    cell.imageView.image = stu.headerImage;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
